clear; clc;
%% Instrument Connection

% Find a serial port object.
obj1 = instrfind('Type', 'serial', 'Port', 'COM8', 'Tag', '');

% Create the serial port object if it does not exist
% otherwise use the object that was found.
if isempty(obj1)
    obj1 = serial('COM8');
else
    fclose(obj1);
    obj1 = obj1(1);
end

% Connect to instrument object, obj1.
fopen(obj1);
% Configure instrument object, obj1.
set(obj1, 'Terminator', {'CR','CR'});
%% Instrument Configuration and Control

% Communicating with instrument object, obj1.
data1 = query(obj1, '*IDN?');
len = int16(str2double( query(obj1, 'DSPN? 0') ));
fstart = str2double( query(obj1, 'FSTR? 0') );
fend   = str2double( query(obj1, 'FEND? 0') );
flist = linspace(fstart, fend, len);

fprintf(obj1, 'PAUS');

fprintf(obj1, '*CLS');
fprintf(obj1, 'DSPY? 0');

str_buff = ''; last_char = '0';
while last_char ~= char(13)
    str_buff = [str_buff, fscanf(obj1, '%c', 512)]; %#ok<AGROW>
    fprintf('%d/%d data is transfered.\n', [length(find(str_buff==',')), len]);
    last_char = str_buff(end);
end
%%
data=str2double(split(str_buff, ','));
loglog(flist, data);

%%
fprintf(obj1, 'STRT');

%% Disconnect and Clean Up

% Disconnect from instrument object, obj1.
fclose(obj1);
